package xiao.trip.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "firstFilter")
public class firstFilter implements Filter {
String[] paths={"/static","/favicon.ico"};
    public void init(FilterConfig config) throws ServletException {
        System.out.println("初始化，在第一次被构建的时候调用一次");
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        System.out.println("doFilter方法被调用");
        HttpServletRequest httpRequest = (HttpServletRequest) req;
        HttpServletResponse httpResponse = (HttpServletResponse) resp;
        HttpSession session = httpRequest.getSession();
        String url=httpRequest.getRequestURI();
        System.out.println(url);
        if (session.getAttribute("username") != null||
                url.equals("/loginCheck")||
                httpRequest.getServletPath().startsWith("/static") ||
                url.equals("/register")
        ) {
            chain.doFilter(req, resp);//登陆成功放行方法
            System.out.println(session.getAttribute("username"));
        }
        //不成功
        else {
            httpResponse.sendRedirect("/loginCheck");
        }
    }
    public void destroy() {
    }
}


